package com.cloud.lawcase.api.provider;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.jdbc.SQL;

import com.cloud.lawcase.api.bean.LawSearchCriteria;

public class ExotericLawPageProvider {
    private static final String SELECT = "t1.law_id, t1.law_code, t1.law_title, t1.law_desc, t1.publish_doc_code, t1.approval_date, t1.publish_date, t1.publish_dept_names, t1.approval_dept_names, t2.law_type_name, t3.region_name, t4.group_code ",
            FROM = "tc_dic_law t1 left join tc_dic_law_type t2 on t1.law_type_id = t2.law_type_id left join tc_dic_law_region t3 on t1.law_region_id = t3.region_id LEFT JOIN tc_dic_law_group t4 ON t1.group_id = t4.group_id ";

    public String listPage(LawSearchCriteria criteria) {
        SQL sql = new SQL().SELECT(SELECT).FROM(FROM);
        sql.WHERE("t1.sx_id = 1");
        if (!StringUtils.isEmpty(criteria.getTitle())) {
            criteria.setTitle("%" + criteria.getTitle() + "%");
            sql.WHERE("t1.law_title like #{title}");
        }
        if (null != criteria.getRegions() && criteria.getRegions().length > 0) {
            StringBuilder region = new StringBuilder();
            boolean b = false;
            for (String r : criteria.getRegions()) {
                if (b) {
                    region.append(", ");
                }
                region.append("'").append(r).append("'");
                b = true;
            }
            region.append(", '000000'");
            sql.WHERE("t1.law_region_id in (" + region.toString() + ")");
        }
        if (criteria.getFuncUnitLevel() > 0) {
            // 职能级别
            sql.WHERE(" t1.law_id in  (SELECT law_id from tc_rel_punish_unit_level WHERE unit_func_level_id = " + criteria.getFuncUnitLevel() + ") ");
        }
        if (StringUtils.isNotEmpty(criteria.getFuncUnitType())) {
            // 职能部门
            sql.WHERE(" t1.law_id in (SELECT law_id from tc_rel_punish_unit_func WHERE unit_func_type_id IN ("+criteria.getFuncUnitType()+")) ");
        }

        if (StringUtils.isNotEmpty(criteria.getCauseID())) {
            sql.WHERE("t1.law_id in (SELECT law_id from tc_dic_law_cause where cause_code in ( "
                    + criteria.getCauseID() + "))");
        }

        return sql.toString();
    }
}
